﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Data.Common;
using Mocola.BLL;
using Mocola.Model;
using Mocola.Net.Web.Utility;
using System.Collections.Generic;
using Mocola.Security;
using Mocola.Web;
using Mocola.Common;

namespace Mocola.Net.Web
{
    public partial class projectgroup : System.Web.UI.Page
    {  
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                int projectid = int.Parse(Request.QueryString["id"]);
                string UsersList=InitCurrentGroup(projectid);
                BindGroup(UsersList);
                CreateTree();
            }
        }

        #region 初始化当前项目组成员
        /// <summary>
        /// 当前用户组
        /// </summary>
        /// <param name="projectid"></param>
        /// <returns></returns>
        private string InitCurrentGroup(int projectid)
        {
            string userid = "";
            string sql = "select * from dbo.Moc_ProjectGroup where projectid={0}";
            sql = string.Format(sql, projectid);
            using (DataTable dt = Databases.MocolaNet.ExecuteDataSet(CommandType.Text, sql).Tables[0])
            {
                if (dt.Rows.Count > 0)
                {
                    ViewState["GroupID"] = dt.Rows[0]["ID"].ToString();
                    txtGroupName.Text = dt.Rows[0]["Name"].ToString();
                    txtExtUser.Text = dt.Rows[0]["ExtEmailList"].ToString();
                    userid = dt.Rows[0]["userslist"].ToString();
                    ViewState["UsersList"] = userid;
                }
                else  //当前项目没有设组成员  将设置默认组名为项目名称
                {
                    sql = "select [name] from Moc_Project where projectid="+projectid;
                    using (IDataReader reader = Databases.MocolaNet.ExecuteReader(CommandType.Text, sql))
                    {
                        if (reader.Read())
                        {
                            txtGroupName.Text = reader["name"].ToString();
                        }
                    }
                }
                return userid;
            }
        }

        private void BindGroup(string userslist)
        {
            if (!string.IsNullOrEmpty(userslist))
            {
                //string sql = "select distinct a.userid,fullname,[name],email from Moc_Users a inner join Moc_DepartmentUser b on a.userid=b.userid inner join Moc_Departments c on c.id=b.departid where a.userid in ({0})";
                string sql = "select distinct a.userid,fullname,email from Moc_Users a where a.userid in ({0})";
                sql = string.Format(sql, userslist);
                DataTable dt = Databases.MocolaNet.ExecuteDataSet(CommandType.Text, sql).Tables[0];
                List<ProjectGroup> list = new List<ProjectGroup>();
                foreach (DataRow row in dt.Rows)
                {
                    ProjectGroup entity = new ProjectGroup();
                    entity.EMail = row["email"].ToString();
                    entity.UserID = row["userid"].ToString();
                    entity.FullName = row["fullname"].ToString();
                    string dept = "";

                    sql = "select name from Moc_DepartmentUser a inner join Moc_Departments b on a.departid=b.id where userid="+row["userid"].ToString ();
                    using (IDataReader reader=Databases.MocolaNet.ExecuteReader(CommandType.Text, sql))
                    {
                        while (reader.Read())
                        {
                            dept += reader["name"]+";";
                        }
                    }
                    entity.Name = dept;
                    list.Add(entity);
                }

                rptGroup.DataSource = list;
                rptGroup.DataBind();
            }
            else
            {
                rptGroup.DataSource = null;
                rptGroup.DataBind();
            }

        }

        #endregion

        #region 选择系统用户
        private void CreateTree()
        {
            DataTable dt = GetUserListAsTable();
            TreeNode root = new TreeNode("部门");           
            using (IDataReader reader = Databases.MocolaNet.Select(Moc_DepartmentsInfo.Moc_Departments, Moc_DepartmentsInfo.Moc_Departments.Name,
                 Moc_DepartmentsInfo.Moc_Departments.ID)
                 .ToDataReader())
            {
                while (reader.Read())
                {
                    TreeNode node = new TreeNode();
                    node.Text = reader["name"].ToString();
                    node.Value = reader["id"].ToString();
                    DataRow[] rows = dt.Select("departid="+reader["id"].ToString ());
                    AddChildNode(node, rows);
                    root.ChildNodes.Add(node);
                }
                reader.Close();
            }
            trDept.Nodes.Add(root);
            trDept.Attributes.Add ("onclick","return getNode(event);");
        }

        /// <summary>
        /// 用户列表
        /// </summary>
        /// <returns></returns>
        private DataTable GetUserListAsTable()
        {
            string sql = "select fullname,a.userid,departid from Moc_Users a inner join Moc_DepartmentUser b on a.userid=b.userid";
            using (DataSet ds = Databases.MocolaNet.ExecuteDataSet(CommandType.Text, sql))
            {
                return ds.Tables[0];
            }
        }
        /// <summary>
        /// 添加部门下面用户的子节点
        /// </summary>
        /// <param name="node"></param>
        /// <param name="rows"></param>
        private void AddChildNode(TreeNode node,DataRow[] rows)
        {
            foreach (DataRow r in rows)
            {
                TreeNode n = new TreeNode();
                n.Text = r["fullname"].ToString();
                n.Value = r["userid"].ToString();
                node.ChildNodes.Add(n);
            }
        }       

        protected void btnOK_Click(object sender, EventArgs e)
        {
            List<string> list = GetCheckedNode(trDept.Nodes);
            if (list.Count > 0)
            {
                string UsersList = "";
                if (ViewState["UsersList"] != null)
                {
                    UsersList = ViewState["UsersList"] as string;
                }
                UsersList =string.IsNullOrEmpty(UsersList)?string.Join(",",list.ToArray()):UsersList+","+string.Join(",", list.ToArray());
                ViewState["UsersList"] = UsersList;
                BindGroup(UsersList);               
            }
        }
        List<string> list = new List<string>();
        private List<string> GetCheckedNode(TreeNodeCollection nodes)
        {
            foreach (TreeNode n in nodes)
            {
                if (n.Depth == 2 && n.Checked)
                {
                    list.Add(n.Value);
                }
                if (n.ChildNodes.Count > 0)
                    list = GetCheckedNode(n.ChildNodes);
            }           
            return list;
        }
        #endregion

        protected void btnDelUser_Click(object sender, EventArgs e)
        {
            RepeaterItem item=(RepeaterItem)((LinkButton)sender).Parent;
            HiddenField hfUserid = item.FindControl("hfUserID") as HiddenField;
            string uid = hfUserid.Value;
            if (ViewState["UsersList"] != null)
            {
                string UserList = ViewState["UsersList"] as string;
                string[] arr = UserList.Split(',');
                List<string> list=new List<string> ();
                foreach(string s in arr)
                {
                    if (!s.Equals(uid))
                        list.Add(s);
                }
                UserList = string.Join(",", list.ToArray());
                ViewState["UsersList"] = UserList;
                BindGroup(UserList);
            }
        }

        protected void rptGroup_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.AlternatingItem || e.Item.ItemType == ListItemType.Item)
            {
                HiddenField hf = e.Item.FindControl("hfUserID") as HiddenField;
                hf.Value = DataBinder.Eval(e.Item.DataItem, "UserID").ToString();
            }
        }


        #region 保存
        protected void btnSave_Click(object sender, EventArgs e)
        {            
            int groupID = -1;
            string msg = "保存成功";
            if (ViewState["GroupID"] != null) //更新
            {
                groupID = int.Parse(ViewState["GroupID"].ToString());
                if (!UpdateUser(groupID))
                    msg = "保存失败！";
            }
            else //新增
            {
                groupID = AddUser();
                if (groupID < 1)
                    msg = "保存失败！";
            }
            Alert.Show(msg);
            ClientScript.RegisterStartupScript(GetType().BaseType, Guid.NewGuid().ToString(),
                "window.parent.MochaUI.closeWindow(window.parent.$('projectGroupManagement'));", true);
        }
        private bool UpdateUser(int groupID)
        {
            DbTransaction transaction = Databases.MocolaNet.BeginTransaction(IsolationLevel.ReadCommitted);
            bool IsResult = true;
            try
            {
                string UsersList = "";
                if (ViewState["UsersList"] != null)
                {
                    UsersList = ViewState["UsersList"].ToString();
                }

                Databases.MocolaNet.Update(Moc_ProjectGroupInfo.Moc_ProjectGroup)
                    .AddColumn(Moc_ProjectGroupInfo.Moc_ProjectGroup.Name,txtGroupName.Text)
                    .AddColumn(Moc_ProjectGroupInfo.Moc_ProjectGroup.UsersList,UsersList)
                    .AddColumn(Moc_ProjectGroupInfo.Moc_ProjectGroup.ExtEmailList,txtExtUser.Text)
                    .Where(Moc_ProjectGroupInfo.Moc_ProjectGroup.ID == groupID)
                    .SetTransaction(transaction)
                    .Execute();
            }
            catch
            {
                IsResult = false;
            }
            finally
            {
                if (IsResult)
                    transaction.Commit();
                else
                    transaction.Rollback();
            }
            return IsResult;
        }
        private int AddUser()
        {
            DbTransaction transaction = Databases.MocolaNet.BeginTransaction(IsolationLevel.ReadCommitted);
            int groupID=-1;
            try
            {
                string UsersList = "";
                if (ViewState["UsersList"] != null)
                {
                    UsersList = ViewState["UsersList"].ToString();
                }
                groupID = Databases.MocolaNet.Insert(Moc_ProjectGroupInfo.Moc_ProjectGroup)
                    .AddColumn(Moc_ProjectGroupInfo.Moc_ProjectGroup.Name,txtGroupName.Text)
                    .AddColumn(Moc_ProjectGroupInfo.Moc_ProjectGroup.UsersList,UsersList)
                    .AddColumn(Moc_ProjectGroupInfo.Moc_ProjectGroup.ExtEmailList,txtExtUser.Text)
                    .AddColumn(Moc_ProjectGroupInfo.Moc_ProjectGroup.ProjectID,Request.QueryString["id"])
                    .SetTransaction(transaction)
                    .Execute();
            }
            catch
            {
                groupID=-1;
            }
            finally
            {
                if (groupID>0)
                    transaction.Commit();
                else
                    transaction.Rollback();                
            }
            return groupID;
        }
        #endregion
    }

    public class ProjectGroup
    {
        private string uid;
        private string fullname;
        private string email;
        private string departname;

        public string UserID
        {
            get { return uid; }
            set { uid = value; }
        }
        public string Name
        {
            get { return departname; }
            set { departname = value; }
        }
        public string EMail
        {
            get { return email; }
            set { email = value; }
        }
        public string FullName
        {
            get { return fullname; }
            set { fullname= value; }
        }
    }
}
